﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace EFCoreLib01
{
    public class UnitOfWorkManager : IUnitOfWorkManager
    {
        private readonly IServiceProvider _serviceProvider;

        public UnitOfWorkManager(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public IUnitOfWorkHandle<TDbContext> Begin<TDbContext>() where TDbContext : DbContext
        {
            var uowHander = AsyncLocalCurrentUnitOfWorkHandleProvider<TDbContext>.Current;
            if (uowHander == null)
            {
                return BeginNew<TDbContext>();
            }
            else
            {
                return new InnerUnitOfWorkHandle<TDbContext>();
            }
        }

        public IUnitOfWorkHandle<TDbContext> BeginNew<TDbContext>() where TDbContext : DbContext
        {
            IServiceScope serviceScope = _serviceProvider.CreateScope();
            var uowHander = new UnitOfWorkHandle<TDbContext>(serviceScope);
            AsyncLocalCurrentUnitOfWorkHandleProvider<TDbContext>.Current = uowHander;

            return uowHander;
        }
    }
}